import { defineStore } from 'pinia'
import { userLogin, userMenus } from '@/api/app'
import { clearStorage, getStorage, setStorage } from '@/utils/localStorage'

const tokenKey = 'x-token'
const profileKey = 'x-admin-profile'
const menusKey = 'x-admin-menus'

export const useAppStore = defineStore('app', {
  state: () => ({
    token: getStorage(tokenKey),
    profile: getStorage(profileKey),
    menus: []
  }),

  actions: {
    login(params: any) {
      return new Promise((resolve, reject) => {
        userLogin(params)
          .then((res) => {
            const { token, profile } = res.data
            this.token = token
            this.profile = profile
            setStorage(tokenKey, token)
            setStorage(profileKey, profile)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    getMenus() {
      return new Promise((resolve, reject) => {
        userMenus()
          .then((res) => {
            this.menus = res.data
            // setStorage(menusKey, res.data)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    logout() {
      this.token = ''
      this.profile = ''
      this.menus = []
      clearStorage()
    }
  }
})
